package com.lebang.service.cences;

import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.CencesObs;
import com.lebang.domain.EarnStatusRecord;
import com.lebang.example.CencesObsExample;
import com.lebang.mapper.AdRecordLogMapper;
import com.lebang.mapper.CencesObsMapper;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.mapper.TaskRouseMapper;
import com.lebang.model.MyConfig;
import com.lebang.model.cences.CencesMsg;
import com.lebang.service.BaseService;
import com.lebang.service.mongodb.CencesMsgMongodb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * cences_obs
 *
 * @Author hwq
 * @Date 2020-07-14
 */
@Service
public class CencesObsService extends BaseService<CencesObs, Integer, CencesObsExample> {
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private CencesObsMapper baseMapper;
    @Autowired
    private TaskRouseMapper taskRouseMapper;
    @Autowired
    private CencesMsgMongodb cencesMsgMongodb;

    @Autowired
    private AdRecordLogMapper adRecordLogMapper;

    public void starDataInit(LocalDateTime end) {
        this.starDataInit(end, null);
    }

    public void starDataInit(LocalDateTime end, List<String> brand) {
        long starTime = System.currentTimeMillis();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime star = end.minusDays(1);
        LocalDate starDate = star.toLocalDate();
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));
        List<CencesObs> cencesMasters = new ArrayList<>();
        if (brand == null) {
            brand = lbbMemberMapper.selectBrand();
        }
        List<String> sdkKey = taskRouseMapper.selectAllKey();

        List<EarnStatusRecord> memberClidkRouseRecords = adRecordLogMapper.selectByDate(star, end);
        memberClidkRouseRecords.forEach(s -> {
            s.setSdkKeyAppStore(s.getAppStore() +  s.getSdkKey()+s.getIsNewMember());
        });
       // Map<String, List<EarnStatusRecord>> clickRecordMap = memberClidkRouseRecords.stream().collect(Collectors.groupingBy(EarnStatusRecord::getSdkKeyAppStore));

        //全部用户的
        List<String> finalBrand = brand;
        sdkKey.forEach(key -> {
            finalBrand.forEach(s -> {
                CencesObs newVo = new CencesObs(0, s, time, 1, key, 0, MyConfig.getEnv());
                CencesObs oldVo = new CencesObs(0, s, time, 0, key, 0,MyConfig.getEnv());
                CencesObs allVo = new CencesObs(0, s, time, 2, key, 1,MyConfig.getEnv());

                countClickV(newVo, oldVo, allVo, s, key, memberClidkRouseRecords, starDate);
                cencesMasters.add(newVo);
                cencesMasters.add(oldVo);
                baseMapper.insertAll(allVo);
                baseMapper.insertAll(newVo);
                baseMapper.insertAll(oldVo);
            });
        });

        //总数计算
        CencesObs item = new CencesObs(0, "all", time, 2, "all", 1,MyConfig.getEnv());
        //新用户全部
        CencesObs newAll = new CencesObs(0, "all", time, 1, "all", 1,MyConfig.getEnv());
        //老用户全部
        CencesObs oldAll = new CencesObs(0, "all", time, 0, "all", 1,MyConfig.getEnv());
        cencesMasters.forEach(vo -> {
            sumBy(item, vo);
            if (vo.getCategory().equals(1)) {
                sumBy(newAll, vo);
            }
            if (vo.getCategory().equals(0)) {
                sumBy(oldAll, vo);
            }

        });
        baseMapper.insertAll(item);
        baseMapper.insertAll(newAll);
        baseMapper.insertAll(oldAll);
        //数据源的全部

        sdkKey.forEach(key -> {
            CencesObs sjy = new CencesObs(0, "all", time, 2, key, 1,MyConfig.getEnv());
            //新用户全部
            CencesObs newAlldata = new CencesObs(0, "all", time, 1, key, 1,MyConfig.getEnv());
            //老用户全部
            CencesObs oldAlldata = new CencesObs(0, "all", time, 0, key, 1,MyConfig.getEnv());
            cencesMasters.forEach(vo -> {
                if (vo.getSdkKey().equals(key)) {
                    sumBy(sjy, vo);
                    if (vo.getCategory().equals(1)) {
                        sumBy(newAlldata, vo);
                    } else {
                        sumBy(oldAlldata, vo);
                    }
                }
            });
            baseMapper.insertAll(sjy);
            baseMapper.insertAll(oldAlldata);
            baseMapper.insertAll(newAlldata);
        });
        //渠道的全部
        brand.forEach(s -> {
            CencesObs sjy = new CencesObs(0, s, time, 2, "all", 1,MyConfig.getEnv());
            //新用户全部
            CencesObs newAlldata = new CencesObs(0, s, time, 1, "all", 1,MyConfig.getEnv());
            //老用户全部
            CencesObs oldAlldata = new CencesObs(0, s, time, 0, "all", 1,MyConfig.getEnv());
            cencesMasters.forEach(vo -> {
                if (vo.getBrand().equals(s)) {
                    sumBy(sjy, vo);
                    if (vo.getCategory().equals(1)) {
                        sumBy(newAlldata, vo);
                    } else {
                        sumBy(oldAlldata, vo);
                    }
                }

            });
            baseMapper.insertAll(sjy);
            baseMapper.insertAll(oldAlldata);
            baseMapper.insertAll(newAlldata);
        });
        cencesMsgMongodb.save(new CencesMsg("每日必赚签到统计", (System.currentTimeMillis() - starTime)));
    }

    private void countClickV(CencesObs newVo, CencesObs oldVo, CencesObs allVo, String s, String key, List<EarnStatusRecord> memberClidkRouseRecords, LocalDate starDate) {
        for (EarnStatusRecord v:memberClidkRouseRecords){
           if(v.getIsNewMember().equals(1)&&v.getAppStore().equals(s)&&key.equals(v.getSdkKey())){
               newVo.setSuccessCount(newVo.getSuccessCount()+v.getStatus());
               newVo.setFailCount(newVo.getFailCount()+v.getHasDeleted());
           }
            if(v.getIsNewMember().equals(0)&&v.getAppStore().equals(s)&&key.equals(v.getSdkKey())){
                oldVo.setSuccessCount(newVo.getSuccessCount()+v.getStatus());
                oldVo.setFailCount(newVo.getFailCount()+v.getHasDeleted());
            }
            if(v.getAppStore().equals(s)&&key.equals(v.getSdkKey())){
                allVo.setSuccessCount(allVo.getSuccessCount()+v.getStatus());
                allVo.setFailCount(allVo.getFailCount()+v.getHasDeleted());
            }
        }
    }

    @DataSource("commonDB")
    public CencesObs sumData(Integer star, Integer end, String appStore, int category, int type, String sdkKey, String likeBrand) {
        return baseMapper.sumData(star, end, appStore, category, type, sdkKey, likeBrand,MyConfig.getEnv());
    }

    private void sumBy(CencesObs item, CencesObs vo) {
        item.setSuccessCount(item.getSuccessCount() + vo.getSuccessCount());
        item.setFailCount(item.getFailCount() + vo.getFailCount());
    }

    private void record(EarnStatusRecord v, CencesObs newVo) {
        //签到数
        if (v.getStatus().equals(1)) {
            newVo.setSuccessCount(newVo.getSuccessCount()+1);
        } else {
            newVo.setFailCount(newVo.getFailCount()+1);
        }

    }

    public int deleteByTime(int time) {
        CencesObsExample earnDayExample = new CencesObsExample();
        earnDayExample.createCriteria().andTimeEqualTo(time).andAppIdEqualTo(MyConfig.getEnv());
        return baseMapper.deleteByExample(earnDayExample);
    }

    /**
     * 统计签到数
     *
     * @param newVo          新用户
     * @param oldVo          老用户
     * @param allVo          全部用户
     * @param appStore       渠道
     * @param clickRecordMap 点击记录
     */
    private void countClick(CencesObs newVo, CencesObs oldVo, CencesObs allVo, String appStore, String sdkKey, Map<String, List<EarnStatusRecord>> clickRecordMap, LocalDate starDate) {
        List<EarnStatusRecord> list = clickRecordMap.get(appStore + sdkKey+1);
        if (null == list) {
            return;
        }
        list.forEach(v -> {
            if (v.getIsNewMember().equals(1)) {
                //今天新增的用户
                this.record(v, newVo);
            } else {
                //老用户
                this.record(v, oldVo);
            }
            this.record(v, allVo);
        });

    }

    @DataSource("commonDB")
    public Long selectCount(CencesObsExample example) {
        return baseMapper.countByExample(example);
    }
    @DataSource("commonDB")
    public List<CencesObs> selectAll(CencesObsExample example) {
        return baseMapper.selectByExample(example);
    }
}
